<template>
  <div class="search-container">
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="0.48rem"
        class="goback"
        @click="$router.go(-1)"
      />
      <!-- 搜索组件 -->
      <van-search
        v-model.trim="keyword"
        v-jujiao
        placeholder="请输入搜索关键词"
        background="#007BFF"
        shape="round"
        @input="getSuggListFn"
        @search="goToResultListPage(keyword)"
      />
    </div>
    <ul class="sugg-list" v-if="this.keyword">
      <li
        class="sugg-item"
        v-for="(item, id) in sugglist"
        :key="id"
        v-html="highlight(item)"
        @click="goToResultListPage(item)"
      ></li>
    </ul>
    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="clearhistoryFn" />
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span
          class="history-item"
          v-for="(qwe, id) in history"
          :key="id"
          @click="goToResultListPage(qwe)"
          @touchstart="touchstarfn(id)"
          @touchmove="touchendfn"
          @touchend="touchendfn"
          >{{ qwe }}</span
        >
      </div>

    </div>
  </div>
</template>

<script>
import { getsugglistAPI } from '@/api/search'
import { Dialog, Toast } from 'vant'
export default {
  data () {
    return {
      keyword: '', // 搜索关键字
      sugglist: [],
      history: JSON.parse(window.localStorage.getItem('history')) || [
        'API',
        'java',
        'css',
        '前端',
        '后台接口',
        'python'
      ] // 搜索历史
    }
  },
  methods: {
    touchstarfn (i) {
      this.timer = setTimeout(async () => {
        try {
          await Dialog.confirm({
            message: '确定删除此条记录吗'
          })
          this.history.splice(i, 1)
          window.localStorage.setItem('history', JSON.stringify(this.history))
        } catch (e) {

        }
      }, 1000)
    },
    touchendfn () {
      clearTimeout(this.timer)
    },
    getSuggListFn () {
      this.timerId && clearTimeout(this.timerId)
      this.timerId = setTimeout(async () => {
        if (!this.keyword) {
          Toast.fail('搜索内容不能为空!')
          return
        }
        const resp = await getsugglistAPI({
          keyword: this.keyword
        })
        // map映射数组,replace查找替换
        const option = resp.data.options.map((item) =>
          item.replace(/[\s?'",]+/g, '')
        )
        this.sugglist = option
      }, 500)
    },
    highlight (item) {
      const regexp = new RegExp(this.keyword, 'gi')
      return item.replace(regexp, (match) => {
        return `<span style='color:red'>${match}</span>`
      })
    },
    goToResultListPage (str) {
      if (this.history.indexOf(str) === -1) {
        this.history.push(str)
      }
      window.localStorage.setItem('history', JSON.stringify(this.history))
      this.$router.push(`/SearchResult/${str}`)
    },
    clearhistoryFn () {
      Dialog.confirm({
        message: '确定清楚所有历史记录吗?'
      })
        .then(() => {
          this.history = []
          window.localStorage.removeItem('history')
        })
        .catch(() => {})
    }
  }

}
</script>

<style scoped lang="less">
.search-header {
  display: flex;
  align-items: center;
  height: 46px;
  background-color: #007bff;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}
/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
